package es.cazadoresmadridejos.beans.controller.adviced;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.pagination.PaginatedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.adviced.AdvicedManager;
import es.cazadoresmadridejos.beans.manager.session.UserPreferences;
import es.cazadoresmadridejos.beans.service.mail.MailService;
import es.cazadoresmadridejos.model.Adviced;
import es.cazadoresmadridejos.objs.web.Page;
import es.cazadoresmadridejos.util.FileUtils.FileType;


@Controller
public class AdvicedListController {

	@Autowired private AdvicedManager advicedManager;
	@Autowired(required=false) private UserPreferences userPreferences;

	@RequestMapping(value="/advicedList*.html")
	public ModelAndView list(
			HttpServletRequest request,
			Boolean isList
			) throws Throwable {

		ModelAndView mv;
		if(Boolean.TRUE.equals(isList)){
			mv = new ModelAndView("advicedList");
		}else{
			mv = new ModelAndView();
		}		

		PaginatedList list = advicedManager.findAllPaginated(new Page(request),userPreferences.getReason().getYear());

		mv.addObject("list", list);

		return mv;
	}


	@RequestMapping(value="/advicedDelete.html")
	public ModelAndView delete(
			@RequestParam(value="id")Long id,
			HttpServletRequest request
			) throws Throwable {

		advicedManager.delete(id);

		return list(request,true);
	}

	@RequestMapping(value="/advicedDownload.html")
	public void download(
			@RequestParam(value="id")Long id,
			HttpServletRequest request,
			HttpServletResponse response
			) throws Throwable {
		OutputStream out = response.getOutputStream();

		Adviced adviced = advicedManager.get(id);
		String root = System.getProperty("catalina.home") + File.separator + FileType.ADVICED.toString() + File.separator;
		File file = new File(root + adviced.getImageUrl());

		int index = adviced.getImageUrl().lastIndexOf(".");
		String ext = adviced.getImageUrl().substring(index);

		response.setContentType( "application/x-download" );
		response.setHeader( "Content-Disposition", "attachment; filename=" + adviced.getTitle() + ext);
		response.setContentLength( (int)file.length() );

		byte[] bbuf = new byte[1024];
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int length; 

		while ((in != null) && ((length = in.read(bbuf)) != -1))
		{
			out.write(bbuf,0,length);
		}

		in.close();
		out.flush();
		out.close();		
	}

}
